package BW_class

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/BW_class"
	BW_classReq "github.com/flipped-aurora/gin-vue-admin/server/model/BW_class/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
)

type ClassService struct {
}

// CreateClass 创建class表记录
// Author [piexlmax](https://github.com/piexlmax)
func (classService *ClassService) CreateClass(class *BW_class.Class) (err error) {
	err = global.GVA_DB.Create(class).Error
	return err
}

// DeleteClass 删除class表记录
// Author [piexlmax](https://github.com/piexlmax)
func (classService *ClassService) DeleteClass(class BW_class.Class) (err error) {
	err = global.GVA_DB.Delete(&class).Error
	return err
}

// DeleteClassByIds 批量删除class表记录
// Author [piexlmax](https://github.com/piexlmax)
func (classService *ClassService) DeleteClassByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]BW_class.Class{}, "id in ?", ids.Ids).Error
	return err
}

// UpdateClass 更新class表记录
// Author [piexlmax](https://github.com/piexlmax)
func (classService *ClassService) UpdateClass(class BW_class.Class) (err error) {
	err = global.GVA_DB.Save(&class).Error
	return err
}

// GetClass 根据id获取class表记录
// Author [piexlmax](https://github.com/piexlmax)
func (classService *ClassService) GetClass(id uint) (class BW_class.Class, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&class).Error
	return
}

// GetClassInfoList 分页获取class表记录
// Author [piexlmax](https://github.com/piexlmax)
func (classService *ClassService) GetClassInfoList(info BW_classReq.ClassSearch) (list []BW_class.Class, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&BW_class.Class{})
	var classs []BW_class.Class
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&classs).Error
	return classs, total, err
}
